package org.buptsse.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.buptsse.ui.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class DocListActivity extends ListActivity {

	private Handler dialogHandler = null;
	private static final int PROGRESSDIALOG = 1;
	private final int finish = 0;
	int page=0,cid=1;
    ArrayList<HashMap<String, String>> discusslist =new ArrayList<HashMap<String,String>>();
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.docdiscuss);
        dialogHandler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case finish:
					SimpleAdapter listAdapter =new SimpleAdapter(DocListActivity.this, discusslist, R.layout.docpost, new String[]{"smalldocname" , "smallusername","time","size"}, new int[]{R.id.docname , R.id.username,R.id.time,R.id.size}); 
			        setListAdapter(listAdapter); 
					dismissDialog(PROGRESSDIALOG);
					break;
				}
			}
		};  
    }
    
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
        if(id==1){  
        	return this.buildProgressDialog(DocListActivity.this);
        }  
        else
        {
        	return null;
        }
    }
    
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(id, dialog);  
        new GetList().start();
    }  
    
    private Dialog buildProgressDialog(Context context)
    {
    	Dialog resultDialog = new ProgressDialog(this);;
    	resultDialog.setTitle("加载中……");
    	((ProgressDialog) resultDialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	return resultDialog;

    }
    
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		showDialog(PROGRESSDIALOG);
	}

	class GetList extends Thread
	{
		public void run()
		{
			GetJsonArray();
			dialogHandler.sendEmptyMessage(finish);
		}
	}
	
	private JSONArray GetJsonArray()
    {
    	HttpClient client=new DefaultHttpClient();
    	StringBuilder builder=new StringBuilder();
    	JSONArray jsonarray=null;
    	HttpPost post=new HttpPost("http://rebook.sinaapp.com/documentlist.php");
    	List<NameValuePair> parameter=new ArrayList<NameValuePair>(); 
    	parameter.add(new BasicNameValuePair("page",String.valueOf(page)));
    	parameter.add(new BasicNameValuePair("cid",String.valueOf(cid)));
    	try {
    		post.setEntity(new UrlEncodedFormEntity(parameter,HTTP.UTF_8));
			HttpResponse response=client.execute(post);
			BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			for(String s=reader.readLine();s!=null;s=reader.readLine())
			{
				builder.append(s);
			}
			if(builder.toString().equals("end"))
			{
				page=page-1;
			}
			else
			{
				jsonarray=new JSONArray(builder.toString());
				JSONObject jsonObject;
				discusslist.clear();
				for(int i=0;i<jsonarray.length();i++)
				{
					jsonObject=jsonarray.getJSONObject(i);
					HashMap<String,String> map=new HashMap<String,String>();
					if(jsonObject.getString("docname").length()>10)
					{
						StringBuffer smalltitle=new StringBuffer(jsonObject.getString("docname").substring(0,9));
						smalltitle.append("……");
						map.put("smalldocname",smalltitle.toString());
					}
					else
					{
						map.put("smalldocname",jsonObject.getString("docname"));
					}
					
					if(jsonObject.getString("username").length()>7)
					{
						StringBuffer smallname=new StringBuffer(jsonObject.getString("username").substring(0,7));
						smallname.append("……");
						map.put("smallusername",smallname.toString());
					}
					else
					{
						map.put("smallusername",jsonObject.getString("username"));
					}
					map.put("username",jsonObject.getString("username"));
					map.put("docname",jsonObject.getString("docname"));
					map.put("time",jsonObject.getString("time"));
					map.put("size",jsonObject.getString("size"));
					map.put("docid",jsonObject.getString("docid"));
					map.put("path",jsonObject.getString("path"));
					discusslist.add(map);
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			System.out.println("client---->"+e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("IO---->"+e.toString());
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("json---->"+e.toString());
			e.printStackTrace();
		}
		return jsonarray;
    }

	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		HashMap map = discusslist.get(position);
		String username = (String) map.get("username");
		String docid=(String)map.get("docid");
		String time=(String)map.get("time");
		String size=(String)map.get("size");
		String title=(String)map.get("docname");
		String path=(String)map.get("path");
		Intent intent=new Intent();
		intent.putExtra("docid",(String)map.get("docid"));
		intent.putExtra("username",username);
		intent.putExtra("time",time);
		intent.putExtra("size",size);
		intent.putExtra("docname",title);
		intent.putExtra("path",path);
		intent.setClass(DocListActivity.this,DocReplyActivity.class);
		DocListActivity.this.startActivity(intent);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menu.add(0, 1, 1, "上一页");
        menu.add(0, 2, 2, "下一页");
        menu.add(0, 3, 3, "上传");
        //menu.add(0,4,4,"上传");
        return super.onCreateOptionsMenu(menu);
    }

public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    if(item.getItemId() == 1){
    	if(page!=0)
    	{
    		page=page-1;
    		showDialog(PROGRESSDIALOG);
    	}
    }
    else if(item.getItemId() == 2){
    	page=page+1;
    	showDialog(PROGRESSDIALOG);
    } 
    else if(item.getItemId()==3)
    {
    	Intent intent=new Intent();
    	intent.setClass(DocListActivity.this,MenuAddGridView.class);
		DocListActivity.this.startActivity(intent);
    }
    return true;
}
}
